import mongoose from 'mongoose';
import Category, { ICategory } from '../models/Category';
import { Request, Response } from 'express';
import moment from 'moment';

// 增加分类
export const addCategory = async (req: Request, res: Response) => {
    try {
        const newCategory = new Category({
            ...req.body, ...{
                createdAt: moment().format('YYYY-MM-DD HH:mm:ss'),
                updatedAt: moment().format('YYYY-MM-DD HH:mm:ss')
            }
        });
        console.log('=====newCategory:', newCategory)
        await newCategory.save();
        res.status(201).json({
            _id: new mongoose.Types.ObjectId(),
            status: 'ok',
            message: '新增分类成功！',
            data: newCategory,
        });
    } catch (error: any) {
        console.error(error.message)
        res.status(500).json({ message: error.message });
    }
};

// 删除分类
export const deleteCategory = async (req: Request, res: Response) => {
    try {
        const { id } = req.params;
        const category = await Category.findByIdAndDelete(id);
        if (!category) {
            return res.status(404).json({ message: '分类未找到' });
        }
        res.json({ message: '分类删除成功' });
    } catch (error: any) {
        res.status(500).json({ message: error.message });
    }
};

// 更新分类
export const updateCategory = async (req: Request, res: Response) => {
    try {
        const { id, data } = req.body;
        const category = await Category.findByIdAndUpdate(id, req.body, { new: true });
        if (!category) {
            return res.status(404).json({ message: '分类未找到' });
        }
        res.json({
            status: 'ok',
            message: '更新分类成功！',
            data: category
        });
    } catch (error: any) {
        res.status(500).json({ message: error.message });
    }
};

// 查询单个分类
export const getCategoryById = async (req: Request, res: Response) => {
    try {
        const { id } = req.params;
        console.log('id:::::', id)
        const category = await Category.findById(id);
        if (!category) {
            return res.status(404).json({ message: '分类未找到' });
        }
        res.json(category);
    } catch (error: any) {
        res.status(500).json({ message: error.message });
    }
};

// 分页查询所有分类
export const getCategories = async (req: Request, res: Response) => {
    try {
        const page = parseInt(req.query.page as string) || 1;
        const limit = parseInt(req.query.limit as string) || 10;
        const skipIndex = (page - 1) * limit;
        const categories = await Category.find().skip(skipIndex).limit(limit);
        const total = await Category.countDocuments();
        res.json({
            total,
            page,
            limit,
            data: categories
        });
    } catch (error: any) {
        res.status(500).json({ message: error.message });
    }
};
